﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Helpers.Http/HttpClientManager 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       HttpClientManager
* 创建时间：  2025/5/21 18:46:32
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Common.Helpers.Http
{
    /// <summary>
    /// 单例调用httpclient
    /// </summary>
    public static class HttpClientManager
    {
        private static Lazy<IHttpClientService> _instance = new Lazy<IHttpClientService>(() =>
        {
            var services = new ServiceCollection();
            services.AddHttpClientService();
            return services.BuildServiceProvider().GetRequiredService<IHttpClientService>();
        }, LazyThreadSafetyMode.ExecutionAndPublication);
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configure"></param>
        public static void Initialize(Action<IServiceCollection> configure)
        {
            var services = new ServiceCollection();
            configure?.Invoke(services);
            services.AddHttpClientService();
            _instance = new Lazy<IHttpClientService>(() =>
                services.BuildServiceProvider().GetRequiredService<IHttpClientService>());
        }

        /// <summary>
        /// httpclient get
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="clientName"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static Task<ServiceResult<T>> GetAsync<T>(string clientName, string url, Dictionary<string, string> data, RequestOptions options = null)
            => _instance.Value.GetAsync<T>(clientName, url, data, options);
        /// <summary>
        /// httpclient post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="clientName"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static Task<ServiceResult<T>> PostAsync<T>(string clientName, string url,
            Dictionary<string, string> data, RequestOptions options = null)
            => _instance.Value.PostAsync<T>(clientName, url, data, options);

    }
}
